import Vue from 'vue'
import ElementUI, {MessageBox} from 'element-ui'
import {Notification} from 'element-ui';
import moment from "moment";
import store from '@/store'

function showMessage(msg, type) {
    ElementUI.Message(
        {
            showClose: true,
            message: msg, type: type,
            center: true,
            customClass: "custom-class",
            offset: 100
        });
}

function showMessageBox(msg, title, type,confirmButton,cancelButton) {
    return MessageBox.confirm(msg, title, {
        confirmButtonText: confirmButton||"确定",
        cancelButtonText: cancelButton||"取消",
        type: type
    })
}

function showNotification(msg, title, type,position) {
    return Notification({
        offset: 200,
        message: msg,
        type: type,
        title: title,
        position: position
    })
}

function showLoading() {
    Vue.prototype.$loading({
        lock: true,
        text: '请稍候，拼命加载中...,',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
        target: loadingDom || 'body'
    })
}

function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if (obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepClone(item);
            return arr;
        }, []);
    }

    if (obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepClone(obj[key]);
            return newObj;
        }, {});
    }
}

// 获取昨天的开始结束时间
function getYesterday() {
    let date = {}
    let start = moment().subtract('days', 1)
    let end = moment().subtract('days', 1)
    date = {
        "start": start,
        "end": end
    }
    return date
}

// 获取最近七天的开始结束时间
function getLast7Days() {
    let date = {}
    let start = moment().subtract('days', 7)
    let end = moment().subtract('days', 1)
    date = {
        "start": start,
        "end": end
    }
    return date
}

// 获取最近30天的开始结束时间
function getLast30Days() {
    let date = {}
    let start = moment().subtract('days', 30)
    let end = moment().subtract('days', 1)
    date = {
        "start": start,
        "end": end
    }
    return date
}

// 获取上一周的开始结束时间
function getLastWeekDays() {
    debugger
    let date = []
    let weekOfday = parseInt(moment().format('d')) // 计算今天是这周第几天  周日为一周中的第一天
    let start = moment().subtract(weekOfday + 7, 'days') // 周一日期
    let end = moment().subtract(weekOfday + 1, 'days') // 周日日期
    date.push(start)
    date.push(end)
    return date
}

// 获取上一个月的开始结束时间
function getLastMonthDays() {
    let date = {}
    let start = moment().subtract('month', 1).format('YYYY-MM') + '-01'
    let end = moment(start).subtract('month', -1).add('days', -1)
    date = {
        "start": start,
        "end": end
    }
    return date
}

function getToday() {
    let date = {}
    const startTime = new Date(new Date(new Date().toLocaleDateString()).getTime())
    const endTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000);
    date = {
        "start": startTime,
        "end": endTime
    }
    console.log("今天开始时间：", date)
    return date;
}

//获取本周的开始结束时间
function getCurrWeekDays() {
    let date = {}
    let weekOfday = parseInt(moment().format('d')) // 计算今天是这周第几天 周日为一周中的第一天
    let start = new Date(new Date(new Date(moment().subtract(weekOfday, 'days')).toLocaleDateString()))// 周一日期
    let end = new Date(new Date(new Date(moment().add(7 - weekOfday - 1, 'days')).toLocaleDateString()).getTime() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000);// 周日日期
    date = {
        "start": start,
        "end": end
    }
    console.log("本周起始时间：", date)

    return date
}

// 获取当前月的开始结束时间
function getCurrMonthDays() {
    let date = {}
    let start = new Date(new Date(new Date(moment().add('month', 0).format('YYYY-MM') + '-01').toLocaleDateString()))
    let end = new Date(new Date(new Date(moment(start).add('month', 1).add('days', -1)).toLocaleDateString()).getTime() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000);
    date = {
        "start": start,
        "end": end
    }
    console.log("本月起始时间：", date)
    return date
}

function validation(productcode, date) {
    console.log("时间格式化：", moment(date).format("YYYY-MM-DD"))
    const time = moment(date).format("YYYY-MM-DD")
    const list = ['1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
        'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    const productInfo = store.state.productInfo
    const serialnodigitsstartindex = productInfo.serialnodigitsstartindex
    const productdatestartindex = productInfo.productdatestartindex
    const code = productcode.substring(productdatestartindex, serialnodigitsstartindex)
    console.log("Code:", code)
    let year = moment(date).format("YYYY")
    const month = moment(date).format("M")
    const day = moment(date).format("D")
    console.log(year + '年' + month + "月" + day + "日")
    let prefix = null
    if (parseInt(year.toString().substring(1, 2)) === 0) {
        prefix = year.toString().substring(0, 2)
        year = year.toString().substring(2, 4)
    } else {
        prefix = year.toString().substring(0, 1)
        year = year.toString().substring(1, 4)
    }
    const yearIndex = parseInt(year) + 1;
    const monthIndex = month - 1
    const dayIndex = day - 1
    console.log(list[yearIndex])
    console.log(list[monthIndex])
    console.log(list[dayIndex])
    const y = code.substring(0, 1)
    const m = code.substring(1, 2)
    const d = code.substring(2, 3)
    console.log("DayCode:", d)
    return {
        result: y === list[yearIndex] && m === list[monthIndex] && d === list[dayIndex],
        time: prefix + (list.indexOf(y) - 1) + '年' + (list.indexOf(m) + 1) + "月" + (list.indexOf(d) + 1) + "日"
    }


}

let loading = false

function openLoading(loadingDom) {
    loading = Vue.prototype.$loading({
        lock: true,
        text: '请稍候，拼命加载中...,',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
        target: loadingDom || 'body'
    })
}

function closeLoading() {
    loading && loading.close()
}

export function startLoading() {
    openLoading()
}

export function endLoading() {
    closeLoading()
}

function getMonthData(date) {
    date = moment(date).format("YYYY-MM-DD")
    console.log("Date:" + date)

    let year = parseInt(moment(date).format("YYYY"))
    const month = parseInt(moment(date).format("M")) - 1


    // 获取当前月份的第一天
    var firstDay = new Date(year, month, 1);

    // 获取下个月的第一天
    var nextMonthFirstDay = new Date(year, month + 1, 1);

    // 计算当前月份的天数
    var daysInMonth = Math.floor((nextMonthFirstDay - firstDay) / (24 * 60 * 60 * 1000));
    // 获取当前月份的所有日期
    var monthData = [];
    for (var i = 1; i <= daysInMonth; i++) {
        var curDate = new Date(year, month, i);
        monthData.push(
            {
                year: year,
                date: moment(curDate).format("MM-DD"),
                day: moment(curDate).format("dddd"),
                dayIndex: i,
            }
        );
    }
    return monthData;
}
function getMonthData1(date) {
    let  nowDay=moment().date();
    date = moment(date).format("YYYY-MM-DD")

    let year = parseInt(moment(date).format("YYYY"))
    const month = parseInt(moment(date).format("M")) - 1

    // 获取当前月份的第一天
    var firstDay = new Date(year, month, 1);
    // 获取下个月的第一天
    var nextMonthFirstDay = new Date(year, month + 1, 1);

    // 计算当前月份的天数
    var daysInMonth = Math.floor((nextMonthFirstDay - firstDay) / (24 * 60 * 60 * 1000));
    // 获取当前月份的所有日期
    var monthData = [];
    for (var i = 1; i <= daysInMonth; i++) {
        var curDate = new Date(year, month, i);
        if(i<=nowDay){

            monthData.push(
                {
                    year: year,
                    date: moment(curDate).format("MM-DD"),
                    day: moment(curDate).format("dddd"),
                    dayIndex: i,
                }
            );
        }

    }
    // monthData=monthData.filter(item=>item.day<=moment(date).format("dddd"))
    // console.log(moment(monthData[monthData.length - 1]).format("YYYY-MM-DD"))
    monthData=  monthData.sort(function(a, b) {
        // 将字符串转换为日期对象
        let dateA = new Date(a.date), dateB = new Date(b.date);

        // 如果dateA在dateB之后，返回正值，导致dateA被移动到后面
        // 如果dateA在dateB之前，返回负值，保持当前顺序
        // 如果它们相等，返回0
        return dateB - dateA; // 注意这里是 dateB - dateA，以实现降序排序
    });
    return monthData;
}

function getMonthAllDate(date) {
    date = moment(date).format("YYYY-MM-DD")
    console.log("Date:" + date)

    let year = parseInt(moment(date).format("YYYY"))
    const month = parseInt(moment(date).format("M")) - 1
    console.log("Year:" + year)
    console.log("Month:" + month)

    // 获取当前月份的第一天
    var firstDay = new Date(year, month, 1);

    // 获取下个月的第一天
    var nextMonthFirstDay = new Date(year, month + 1, 1);

    // 计算当前月份的天数
    var daysInMonth = Math.floor((nextMonthFirstDay - firstDay) / (24 * 60 * 60 * 1000));
    // 获取当前月份的所有日期
    var monthData = [];
    for (var i = 1; i <= daysInMonth; i++) {
        var curDate = new Date(year, month, i);
        monthData.push(
            {
                rosteringDate: moment(curDate).format("YYYY-MM-DD"),
                week: moment(curDate).format("E")
            }
        );
    }
    return monthData;
}


function getMonthAllDate1(date) {
    date = moment(date).format("YYYY-MM-DD")
    console.log("Date:" + date)

    let year = parseInt(moment(date).format("YYYY"))
    const month = parseInt(moment(date).format("M")) - 1
    console.log("Year:" + year)
    console.log("Month:" + month)

    // 获取当前月份的第一天
    var firstDay = new Date(year, month, 1);

    // 获取下个月的第一天
    var nextMonthFirstDay = new Date(year, month + 1, 1);

    // 计算当前月份的天数
    var daysInMonth = Math.floor((nextMonthFirstDay - firstDay) / (24 * 60 * 60 * 1000));
    // 获取当前月份的所有日期
    var monthData = [];
    for (var i = 1; i <= daysInMonth; i++) {
        var curDate = new Date(year, month, i);
        monthData.push(
            {
                rosteringDate: moment(curDate).format("YYYY-MM-DD"),
                week: moment(curDate).format("E")
            }
        );
    }
    monthData=monthData.sort(function(a, b) {
        // 将字符串转换为日期对象
        let dateA = new Date(a.rosteringDate), dateB = new Date(b.rosteringDate);

        // 如果dateA在dateB之后，返回正值，导致dateA被移动到后面
        // 如果dateA在dateB之前，返回负值，保持当前顺序
        // 如果它们相等，返回0
        return dateB - dateA; // 注意这里是 dateB - dateA，以实现降序排序
    });
    return monthData;
}

function getWeekIndex(data) {
    let weeks = data.split("到")

}

function notify(message, title, warning) {
    this.$notify({
        title: title,
        message: message,
        type: warning
    });
}
function uniqueSortObjects(arr, prop) {
    // 使用 Set 对象去重
    const uniqueObjects = [...new Set(arr.map(item => item[prop]))]
        .map(id => arr.find(obj => obj[prop] === id));

    // 对结果数组进行排序
    uniqueObjects.sort((a, b) => a[prop] - b[prop]);

    return uniqueObjects;
}
const tools = {
    showMessage,
    showMessageBox,
    showNotification,
    getCurrMonthDays,
    getCurrWeekDays,
    getLastWeekDays,
    getToday,
    openLoading,
    closeLoading,
    validation,
    getMonthData,
    getMonthData1,
    getMonthAllDate,
    getMonthAllDate1,
    deepClone,
    uniqueSortObjects
}

export default tools;
